package cn.whdream.test.entity;

import org.mybatis.dynamic.sql.AbstractSingleValueCondition;
import org.mybatis.dynamic.sql.BindableColumn;
import org.mybatis.dynamic.sql.VisitableCondition;
import org.mybatis.dynamic.sql.render.TableAliasCalculator;
import org.mybatis.dynamic.sql.select.function.AbstractFunction;

import java.util.Objects;

public class Or<T> extends AbstractFunction<T, Or<T>> {

    public static final String CONNECTOR = " or";
    private BindableColumn<T>  secondColumn;
    private AbstractSingleValueCondition<T> firstCondition;

    private BindableColumn<T> thirdColumn;
    private BindableColumn<T> fourthColumn;
    private AbstractSingleValueCondition<T> secondCondition;

    protected Or(BindableColumn<T> firstColumn,BindableColumn<T> secondColumn) {
        super(firstColumn);
        this.secondColumn = Objects.requireNonNull(secondColumn);
    }

    public Or(BindableColumn<T> column, AbstractSingleValueCondition<T> firstCondition,  BindableColumn<T> secondColumn,AbstractSingleValueCondition<T> secondCondition) {
        super(column);
        this.secondColumn = Objects.requireNonNull(secondColumn);
        this.firstCondition = Objects.requireNonNull(firstCondition);
        this.secondCondition = Objects.requireNonNull(secondCondition);
    }

    @Override
    protected Or<T> copy() {
        return new Or<>(column,secondColumn);
    }

    @Override
    public String renderWithTableAlias(TableAliasCalculator tableAliasCalculator) {
        if (thirdColumn == null){
            return column+" "+ CONNECTOR +" "+secondColumn.renderWithTableAlias(tableAliasCalculator);
        }
        return packColumns(column,firstCondition,tableAliasCalculator) + CONNECTOR + packColumns(secondColumn,secondCondition, tableAliasCalculator);
    }

    private String packColumns(BindableColumn<T> column, AbstractSingleValueCondition<T> firstCondition, TableAliasCalculator tableAliasCalculator) {
      //  return " ( "+firstCondition.renderCondition(column.renderWithTableAlias(tableAliasCalculator),firstCondition.value())+" ) ";
        return "";
    }


    public static <T> Or<T> of(BindableColumn<T> column,BindableColumn<T> secondColumn){
        return new Or<>(column,secondColumn);
    }


    public static <T> Or<T> of(BindableColumn<T> column, AbstractSingleValueCondition<T> firstCondition,  BindableColumn<T> secondColumn,AbstractSingleValueCondition<T> secondCondition){
        return new Or<>(column,firstCondition,secondColumn,secondCondition) ;
    }
}
